<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !modifyBatchInfo.visible &&
        !detailInfo.visible &&
        !equipmentDetailInfo.visible &&
        !assetDetailInfo.visible &&
        !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
        <!--   <el-button
          @click="detailListInfo.visible = true"
          v-if="$permission('assetInstrumentsPlan:history')"
          >历史记录</el-button
        > -->
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-batchEntry>
            <el-button :disabled="!canBatchEntry" @click="batchEntry()"
              >批量录入</el-button
            >
          </template>
          <template v-slot:filter-uploadResult>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importResult"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入检定结果</el-button>
            </el-upload>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :checkBox="true"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-assetName="scope">
          <span
            v-if="scope.row.assetName"
            class="slip-edit"
            @click="showAssetDetail(scope.row)"
            >{{ scope.row.assetName }}</span
          >
          <span v-else>
            {{ '-' }}
          </span>
        </template>
        <template v-slot:col-commonName="scope">
          <span class="slip-edit" @click="showEquipmentDetail(scope.row)">{{
            scope.row.commonName
          }}</span>
        </template>
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </TableContainer>
    </div>

    <asset-instruments-plan-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :plan-id="modifyInfo.planId"
      @returnModify="returnModify"
    />
    <modify-batch
      v-if="modifyBatchInfo.visible"
      v-model:visible="modifyBatchInfo.visible"
      :title="modifyBatchInfo.title"
      :rows="tableInfo.selections"
      @returnModify="returnModify"
    />
    <!--  <asset-instruments-plan-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="returnDetail"
    /> -->
    <!-- 资产详情页 -->
    <assetArchives-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
      @returnBack="getList"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <!-- 详情-->
    <equipment-archives-details
      v-if="equipmentDetailInfo.visible"
      v-model:visible="equipmentDetailInfo.visible"
      :title="equipmentDetailInfo.title"
      :id="equipmentDetailInfo.id"
      @returnBack="returnDetail"
    />
    <!-- 详情-->
    <AssetInstrumentsPlanDetail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :orderId="detailInfo.orderId"
      @returnBack="returnDetail"
    />
  </div>
</template>

<script setup name="assetInstrumentsPlan">
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import {
  getMeasuringVerificationTaskPage,
  cancelMeasuringVerificationTask,
} from '@/api/quality.js'
import { exportTemplateExcel } from '@/api/pub.js'
import AssetInstrumentsPlanModify from './modify'
import modifyBatch from './modifyBatch'
import EquipmentArchivesDetails from './../../settings/measuringInstrument/details.vue'
import AssetInstrumentsPlanDetail from './detail'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import AssetArchivesDetail from '@/views/asset/assetManage/assetCard/details'
const detailList = defineAsyncComponent(() => import('./detailList'))
// 过滤相关配置
const { proxy } = getCurrentInstance()
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      orgId: {
        asTbName: 'measuring_verification_task',
        columnName: 'org_id',
        queryResource: 0,
        queryType: 'IN',
        queryCategory: 'AND',
        value: proxy.$store.state.user.userInfo.user.orgId,
      },
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'batchEntry',
      show: proxy.$permission('assetInstrumentsPlan:import'),
    },
    /* {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('assetInstrumentsPlan:download'),
    },
    {
      type: 'slot',
      value: 'uploadResult',
      show: proxy.$permission('assetInstrumentsPlan:import'),
    }, */
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '180',
    btList: [
      {
        label: '录入检定结果',
        event: entry,
        show: proxy.$permission('assetInstrumentsPlan:entry'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '取消任务',
        event: cancel,
        popconfirmText: '取消任务后将改变数据,是否继续？',
        show: proxy.$permission('assetInstrumentsPlan:cancel'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
    ],
  },
})
const uploadInfo = ref({
  action:
    axios.defaults.baseURL +
    '/asset/assetManage/instrumentsRecord/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const modifyInfo = ref({
  visible: false,
  planId: '',
  title: '',
})
const modifyBatchInfo = ref({
  visible: false,
  planId: '',
  title: '',
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const equipmentDetailInfo = ref({
  visible: false,
  id: '',
})
const detailListInfo = ref({
  visible: false,
})
//明细相关
const assetDetailInfo = ref({
  visible: false,
  title: '资产档案明细',
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const canBatchEntry = computed(() => {
  return (
    tableInfo.value.selections.length > 0 &&
    !tableInfo.value.selections.filter((item) => item.status !== 1).length
  )
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'assetInstrumentsPlan' && el.url === val.url) {
                detailInfo.value.visible = false
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.orderId = val.businessId
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                } else if (val.urlType === 3) {
                  proxy.$nextTick(() => {
                    modifyInfo.value.title = '录入检定结果'
                    modifyInfo.value.visible = true
                    modifyInfo.value.planId = val.businessId
                    modifyInfo.value.orderId = val.businessId
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
function downloadTemplate() {
  exportTemplateExcel('asset_instruments_record').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function importResult(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}
function returnModify() {
  modifyInfo.value.visible = false
  getList()
}
function returnDetail() {
  detailInfo.value.visible = false
  getList()
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function cancel(row) {
  cancelMeasuringVerificationTask([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//录入
function entry(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.planId = row.id
  modifyInfo.value.title = '录入检定结果'
  modifyInfo.value.visible = true
}
function batchEntry() {
  modifyBatchInfo.value.title = '批量录入检定结果'
  modifyBatchInfo.value.visible = true
}
//展示资产明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.orderId = row.id
  detailInfo.value.visible = true
}
function showAssetDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
//展示计划明细
function showEquipmentDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  equipmentDetailInfo.value.id = row.measuringInstrumentId
  equipmentDetailInfo.value.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'measuringVerificationTaskList-com.slip.spd.entity.vo.quality.MeasuringVerificationTaskVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getMeasuringVerificationTaskPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

let obj = {
  isMandatoryInspection: {
    label: '是否强检',
    value: 'isMandatoryInspection',
    componentType: 'select-model',
    code: 'yes_or_no',
    show: false,
    hidden: true,
  },
  useStatus: {
    label: '使用状态',
    value: 'useStatus',
    componentType: 'select-model',
    code: 'asset_font_status',
    show: false,
    hidden: true,
  },
  preVerificationDate: {
    label: '上次检定日期',
    value: 'preVerificationDate',
    componentType: 'date',
    show: false,
    hidden: true,
  },
  preVerificationPeriod: {
    label: '检定周期',
    value: 'preVerificationPeriod',
    componentType: 'number',
    show: true,
    hidden: true,
  },
  checkDatePlan: {
    label: '计划检定日期',
    value: 'checkDatePlan',
    componentType: 'date',
    show: false,
    hidden: true,
  },
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  orderNo: {
    label: '任务编号',
    value: 'orderNo',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
